import { NestFactory, repl } from '@nestjs/core';
import { AppModule } from './modules/app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { json } from 'express';
import * as jsyaml from 'js-yaml';
import * as fs from 'fs';
import * as compression from 'compression';
import { ResponseInterceptor } from './interceptor/response.interceptor';
import { HttpExceptionFilter } from './filter/http-exception.filter';
import dto2zod from 'dto-to-zod';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  /**
   * 本地开发环境才生效
   */
  if (process.env.NODE_ENV==='localhost') {
    /** 
     * swagger
     */
    const options = new DocumentBuilder()
      // .setTitle('Swagger文档')
      // .setDescription('swagger调试文档')
      .setVersion('1.0')
      .addTag('swagger')
      /** Bearer认证 */
      .addBearerAuth()
      .build();
    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup('swagger', app, document);
    /** 转为yaml格式来保存 */
    const yamlDocument = jsyaml.dump(document, {
      skipInvalid: true,
      noRefs: true
    });
    fs.writeFile('./swagger.yaml', yamlDocument, ()=>{console.log('>>>swagger.yaml文档已更新')});

    /** webpack 热重载 */
    if (module.hot) {
      module.hot.accept();
      module.hot.dispose(() => app.close());
    }

    /** repl工具 */
    repl(AppModule);

    /** dto转zod */
    dto2zod('./src/types', [/^.*?.(dto|vo).ts$/]);
  }

  /** 允许跨域 */
  app.enableCors({
    /** 不配origin, credentials低代码数据源请求报错!! */
    origin: "*",
    credentials: true,
  });
  /** 响应gzip压缩 */
  app.use(((<typeof compression & {default: typeof compression}>compression).default || compression)());
  /** http异常过滤器 */
  app.useGlobalFilters(new HttpExceptionFilter());
  /** 响应拦截器 */
  app.useGlobalInterceptors(new ResponseInterceptor());
  /** 请求大小限制更改到 */
  app.use(json({limit: '2mb'}));
  await app.listen(9000);
}
bootstrap();

declare const module: any;